package com.dci.controller.schedule;


import com.dci.model.schedule.ProjectNodeInfo;
import com.dci.model.schedule.ScheduleTrackInfo;
import com.dci.result.JsonData;
import com.dci.result.PageResult;
import com.dci.service.node.NodeInfoService;
import com.dci.service.node.ProjectNodeInfoService;
import com.dci.service.schedule.ScheduleTrackInfoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * All rights Reserved, Designed By 姑苏区政府大数据中心
 *
 * @version V1.0
 * @Title: null.java
 * @Package com.dci.controller.project
 * @Description: 进度跟踪
 * @author: 张星亮
 * @date: 2019/2/25
 * @Copyright: 2019 姑苏区政府大数据中心. All rights reserved.
 * 注意：本内容仅限于姑苏区政府大数据中心内部传阅，禁止外泄以及用于其他的商业目
 */
@Controller
@RequestMapping("/schedule")
public class ScheduleTrackController {

    @Resource
    private ScheduleTrackInfoService scheduleTrackInfoService;


    @Resource
    private ProjectNodeInfoService projectNodeInfoService;

    @Resource
    private NodeInfoService nodeInfoService;

    @Value("${upload.path}")
    private String path;
    @Value("${upload.urlP}")
    private String urlP;

    /**
     * 新增项目流程获取url
     *
     * @param record
     * @return JsonData 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping("/insert")
    @ResponseBody
    public JsonData insert(@RequestBody ScheduleTrackInfo record) {
        Date now = new Date();
        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
        String address = df.format(now);
        String filePath = urlP + address + "/";
        record.setFile_url(filePath);
        try {
            return scheduleTrackInfoService.insert(record);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonData.success(null, 911);
        }
    }


    /**
     * 项目流程上传文件
     *
     * @param files
     * @param id
     * @param number
     * @param file_url
     * @param node_name
     * @return
     */
    @RequestMapping("/save")
    @ResponseBody
    public JsonData insert(@RequestParam("uploadFile") MultipartFile[] files, @RequestParam("id") String id, @RequestParam("node_number") String number, @RequestParam("file_url") String file_url, @RequestParam("node_name") String node_name) {
        ScheduleTrackInfo record = new ScheduleTrackInfo();
        record.setFile_url(file_url);
        record.setId(id);
        record.setNode_number(Integer.valueOf(number));
        if (record.getFile_url() == null && record.getNodeStatus() == 0) {
            Date now = new Date();
            SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
            String address = df.format(now);
            String filePath = path + File.separator + address + "/";
            String fileNames = "";
            if (files.length != 0) {
                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename();
                    if (fileNames == "") {
                        fileNames += fileName;
                    } else {
                        fileNames += ',' + fileName;
                    }
                    File fileDir = new File(filePath);
                    if (!fileDir.exists()) {
                        fileDir.mkdirs();
                    }
                    try {
                        file.transferTo(new File(fileDir.getAbsolutePath(), fileName));
                    } catch (IOException e) {
                        continue;
                    }
                }
            }
            String urlPath = urlP + address + "/";
            record.setFile_url(urlPath);
            record.setApproval_file(fileNames);
        } else {
            String fileNames = "";
            String url = record.getFile_url();
            String result = "";
            int i = 0;
            while (i < 2) {
                int lastFirst = url.lastIndexOf('/');
                result = url.substring(lastFirst) + result;
                url = url.substring(0, lastFirst);
                i++;
            }
            String P = result.substring(1);
            String filePath = path + "/" + P;
            if (files.length != 0) {
                for (MultipartFile file : files) {
                    String fileName = file.getOriginalFilename();
                    if (fileNames == "") {
                        fileNames += fileName;
                    } else {
                        fileNames += ',' + fileName;
                    }
                    File fileDir = new File(filePath);
                    if (!fileDir.exists()) {
                        fileDir.mkdirs();
                    }
                    try {
                        file.transferTo(new File(fileDir.getAbsolutePath(), fileName));
                    } catch (IOException e) {
                        continue;
                    }
                }
            }
            switch (node_name) {
                case "立项":
                    record.setApproval_file(fileNames);
                    break;
                case "招标":
                    record.setTend_file(fileNames);
                    break;
                case "施工":
                    record.setConstruction_file(fileNames);
                    break;
                case "验收":
                    record.setCheck_file(fileNames);
                    break;
                case "审计":
                    record.setAudit_file(fileNames);
                    break;
                default:
                    break;
            }
            ProjectNodeInfo projectNodeInfo = new ProjectNodeInfo();
            projectNodeInfo.setProjectId(id);
            List<ProjectNodeInfo> list = nodeInfoService.selectByProjectId(projectNodeInfo);
            int a = record.getNode_number();
            int b = record.getNode_number();
            if (a < list.size() - 1) {
                record.setNode_name(list.get(a + 1).getNodeName());
            } else if (a == list.size() - 1) {
                record.setNodeStatus(1);
            }
            record.setNode_number(b + 1);
        }
        try {
            return scheduleTrackInfoService.insertAll(record);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonData.success(null, 911);
        }
    }

    /**
     * 修改项目流程
     *
     * @param record
     * @return JsonData 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping("/update")
    @ResponseBody
    public JsonData update(@RequestBody ScheduleTrackInfo record) {
        try {
            return scheduleTrackInfoService.update(record);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonData.success(null, 911);
        }
    }


    /**
     * 查询获取列表, 分页
     *
     * @param record
     * @return JsonData 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @ResponseBody
    @RequestMapping("/getPageList")
    public PageResult selectPageList(@RequestBody ScheduleTrackInfo record) {
        try {
            return scheduleTrackInfoService.selectPageList(record);
        } catch (Exception e) {
            return PageResult.fail(911);
        }
    }


    /**
     * 根据项目 id 获取关联节点信息
     *
     * @param record
     * @return JsonData 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping("/getNodeList")
    @ResponseBody
    public JsonData getNodeList(@RequestBody ProjectNodeInfo record) {
        JsonData data = projectNodeInfoService.selectByProjectId(record);
        Object o = data.getData();

        try {
            return projectNodeInfoService.selectByProjectId(record);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonData.success(null, 911);
        }
    }


    /**
     * 删除项目
     *
     * @param list
     * @return JsonData 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @PostMapping("/delete")
    @ResponseBody
    public JsonData deleteProject(@RequestBody List<ScheduleTrackInfo> list) {
        try {
            return scheduleTrackInfoService.batchDelete(list);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonData.success(null, 911);
        }
    }


    /**
     * 查询
     *
     * @param record
     * @return JsonData 封装的返回参数  保存成功msg:906 保存失败msg:911
     */
    @RequestMapping("/getShowScheduleNodeInfo")
    @ResponseBody
    public PageResult getShowScheduleNodeInfo(@RequestBody ScheduleTrackInfo record) {
        PageResult res = scheduleTrackInfoService.getShowScheduleNodeInfo(record);
        try {
            return scheduleTrackInfoService.getShowScheduleNodeInfo(record);
        } catch (Exception e) {
            e.printStackTrace();
            return PageResult.fail(911);
        }
    }

}
